<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="include :: header('PK答题')" />
    <style>
        .exam-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        .exam-header {
            background: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }
        .exam-title {
            font-size: 24px;
            font-weight: bold;
            color: #333;
            margin-bottom: 10px;
        }
        .exam-info {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
        }
        .exam-meta {
            font-size: 16px;
            color: #666;
        }
        .exam-timer {
            font-size: 20px;
            font-weight: bold;
            color: #f5222d;
        }
        .question-area {
            background: #fff;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }
        .question-title {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 20px;
            color: #333;
        }
        .question-options {
            margin-bottom: 30px;
        }
        .option-item {
            padding: 12px 15px;
            margin-bottom: 10px;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s;
        }
        .option-item:hover {
            border-color: #40a9ff;
            background-color: #e6f7ff;
        }
        .option-item.selected {
            border-color: #1890ff;
            background-color: #e6f7ff;
            font-weight: bold;
        }
        .option-item input[type="radio"],
        .option-item input[type="checkbox"] {
            margin-right: 10px;
        }
        .question-nav {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .progress-info {
            font-size: 16px;
            color: #666;
        }
        .navigation-buttons {
            text-align: center;
            margin-top: 20px;
        }
        .question-nav-list {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            justify-content: center;
            margin: 20px 0;
        }
        .question-nav-item {
            width: 36px;
            height: 36px;
            line-height: 36px;
            text-align: center;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s;
        }
        .question-nav-item:hover {
            border-color: #40a9ff;
            background-color: #e6f7ff;
        }
        .question-nav-item.active {
            border-color: #1890ff;
            background-color: #1890ff;
            color: #fff;
        }
        .question-nav-item.answered {
            background-color: #f6ffed;
            border-color: #b7eb8f;
        }
        .btn-submit-answer {
            background-color: #52c41a;
            border-color: #52c41a;
        }
        .btn-submit-answer:hover {
            background-color: #73d13d;
            border-color: #73d13d;
        }
    </style>
</head>
<body class="gray-bg">
    <div class="exam-container">
        <div class="exam-header">
            <div class="exam-title" id="examTitle">PK答题</div>
            <div class="exam-info">
                <div class="exam-meta">
                    <span>对战编号：<span id="battleNo">加载中...</span></span> |
                    <span>对手：<span id="opponent">加载中...</span></span>
                </div>
                <div class="exam-timer">
                    <i class="fa fa-clock-o"></i> <span id="timer">00:00:00</span>
                </div>
            </div>
        </div>
        
        <div class="question-area">
            <div class="question-title">
                <span id="question-number">第1题</span> / <span id="total-questions">0题</span> - 
                <span id="question-type">单选题</span>
            </div>
            
            <div class="question-content" id="question-content">
                <!-- 题目内容将通过JavaScript动态加载 -->
            </div>
            
            <div class="question-options" id="question-options">
                <!-- 题目选项将通过JavaScript动态加载 -->
            </div>
            
            <div class="question-nav">
                <div class="progress-info">
                    <p>答题进度：<span id="current-num">1</span>/<span id="total-num">0</span></p>
                </div>
                
                <div class="navigation-buttons">
                    <button class="btn btn-default" id="prevBtn" disabled>
                        <i class="fa fa-arrow-left"></i> 上一题
                    </button>
                    <button class="btn btn-primary btn-submit-answer" id="submitBtn">
                        <i class="fa fa-check"></i> 提交答案
                    </button>
                    <button class="btn btn-default" id="nextBtn" disabled>
                        下一题 <i class="fa fa-arrow-right"></i>
                    </button>
                    <button class="btn btn-warning" id="finishBtn" style="display:none;">
                        <i class="fa fa-flag"></i> 结束答题
                    </button>
                </div>
            </div>
            
            <div class="question-nav-list" id="question-nav-list">
                <!-- 题目导航将通过JavaScript动态生成 -->
            </div>
        </div>
    </div>
    
    <th:block th:include="include :: footer" />
    
    <script type="text/javascript">
        // 答题数据
        var examData = {
            battleId: null, // PK对战ID
            configId: null,
            examType: 2, // PK答题类型
            questions: [], // 题目列表
            currentQuestionIndex: 0, // 当前题目索引
            answers: {}, // 用户答案记录
            startTime: new Date(), // 开始时间
            timerInterval: null, // 计时器
            remainingTime: 0 // 剩余时间（秒）
        };
        
        $(function() {
            // 解析URL参数
            var urlParams = new URLSearchParams(window.location.search);
            examData.battleId = urlParams.get('battleId');
            
            if (!examData.battleId) {
                $.modal.alertError('缺少对战ID参数', function() {
                    history.back();
                });
                return;
            }
            
            // 加载对战信息和题目
            loadBattleInfo();
        });
        
        // 加载对战信息
        function loadBattleInfo() {
            // 这里应该通过AJAX加载对战信息和题目
            // 暂时使用模拟数据
            loadQuestions();
        }
        
        // 加载题目数据（模拟）
        function loadQuestions() {
            // 模拟题目数据
            examData.questions = [
                {
                    id: 1,
                    questionType: 1, // 单选题
                    questionContent: "中国共产党成立于哪一年？",
                    optionA: "1919年",
                    optionB: "1921年",
                    optionC: "1923年",
                    optionD: "1925年",
                    correctAnswer: "B"
                },
                {
                    id: 2,
                    questionType: 2, // 多选题
                    questionContent: "以下哪些是中国共产党的指导思想？",
                    optionA: "马克思列宁主义",
                    optionB: "毛泽东思想",
                    optionC: "邓小平理论",
                    optionD: "三个代表重要思想",
                    correctAnswer: "ABCD"
                },
                {
                    id: 3,
                    questionType: 3, // 判断题
                    questionContent: "中国共产党是中国工人阶级的先锋队，同时是中国人民和中华民族的先锋队。",
                    optionA: "正确",
                    optionB: "错误",
                    correctAnswer: "A"
                },
                {
                    id: 4,
                    questionType: 4, // 填空题
                    questionContent: "中国共产党的根本宗旨是______。",
                    correctAnswer: "全心全意为人民服务"
                }
            ];
            
            // 设置考试时长（默认1小时）
            examData.remainingTime = 3600;
            
            // 显示题目总数
            $('#total-num').text(examData.questions.length);
            $('#total-questions').text(examData.questions.length + '题');
            
            // 初始化显示第一题
            if (examData.questions.length > 0) {
                showQuestion(0);
                updateQuestionNav();
                startTimer();
            } else {
                $('#question-content').html('<div class="alert alert-warning">暂无题目，请联系管理员。</div>');
            }
        }
        
        // 显示指定题目
        function showQuestion(index) {
            if (index < 0 || index >= examData.questions.length) return;
            
            examData.currentQuestionIndex = index;
            var question = examData.questions[index];
            
            // 更新进度显示
            $('#current-num').text(index + 1);
            $('#question-number').text('第' + (index + 1) + '题');
            
            // 显示题目内容
            $('#question-content').html('<p>' + question.questionContent + '</p>');
            
            // 显示题目类型
            var typeText = getQuestionTypeText(question.questionType);
            $('#question-type').text(typeText);
            
            // 构造选项HTML
            var optionsHtml = '';
            var userAnswer = examData.answers[question.id] || '';
            
            if (question.questionType === 1) { // 单选题
                optionsHtml += createOptionItem('A', question.optionA, userAnswer === 'A', 'radio');
                optionsHtml += createOptionItem('B', question.optionB, userAnswer === 'B', 'radio');
                optionsHtml += createOptionItem('C', question.optionC, userAnswer === 'C', 'radio');
                optionsHtml += createOptionItem('D', question.optionD, userAnswer === 'D', 'radio');
            } else if (question.questionType === 2) { // 多选题
                var selectedOptions = userAnswer.split('');
                optionsHtml += createOptionItem('A', question.optionA, selectedOptions.includes('A'), 'checkbox');
                optionsHtml += createOptionItem('B', question.optionB, selectedOptions.includes('B'), 'checkbox');
                optionsHtml += createOptionItem('C', question.optionC, selectedOptions.includes('C'), 'checkbox');
                optionsHtml += createOptionItem('D', question.optionD, selectedOptions.includes('D'), 'checkbox');
            } else if (question.questionType === 3) { // 判断题
                optionsHtml += createOptionItem('A', question.optionA, userAnswer === 'A', 'radio');
                optionsHtml += createOptionItem('B', question.optionB, userAnswer === 'B', 'radio');
            } else if (question.questionType === 4) { // 填空题
                optionsHtml += '<div class="form-group">';
                optionsHtml += '  <input type="text" class="form-control" id="fillBlankInput" placeholder="请输入答案" value="' + userAnswer + '">';
                optionsHtml += '</div>';
            }
            
            $('#question-options').html(optionsHtml);
            
            // 绑定选项点击事件
            if (question.questionType !== 4) {
                $('.option-item').on('click', function() {
                    selectOption($(this), question.questionType);
                });
            }
            
            // 更新导航按钮状态
            updateNavigationButtons();
        }
        
        // 创建选项元素
        function createOptionItem(option, content, isSelected, type) {
            var html = '';
            var checkedAttr = isSelected ? 'checked' : '';
            var selectedClass = isSelected ? 'selected' : '';
            
            html += '<div class="option-item ' + selectedClass + '" data-option="' + option + '">';
            html += '  <input type="' + type + '" name="question-option" value="' + option + '" ' + checkedAttr + '> ' + option + '. ' + content;
            html += '</div>';
            
            return html;
        }
        
        // 选择选项
        function selectOption(element, questionType) {
            var question = examData.questions[examData.currentQuestionIndex];
            var option = element.data('option');
            
            if (questionType === 1 || questionType === 3) { // 单选题或判断题
                // 清除其他选项的选中状态
                $('.option-item').removeClass('selected');
                $('input[name="question-option"]').prop('checked', false);
                
                // 选中当前选项
                element.addClass('selected');
                element.find('input').prop('checked', true);
                
                // 记录答案
                examData.answers[question.id] = option;
            } else if (questionType === 2) { // 多选题
                // 切换当前选项的选中状态
                element.toggleClass('selected');
                var isChecked = element.hasClass('selected');
                element.find('input').prop('checked', isChecked);
                
                // 收集所有选中的选项
                var selectedOptions = [];
                $('.option-item.selected').each(function() {
                    selectedOptions.push($(this).data('option'));
                });
                
                // 记录答案
                examData.answers[question.id] = selectedOptions.sort().join('');
            }
            
            // 更新导航按钮状态
            updateNavigationButtons();
            
            // 更新题目导航
            updateQuestionNav();
        }
        
        // 填空题答案输入事件
        $(document).on('input', '#fillBlankInput', function() {
            var question = examData.questions[examData.currentQuestionIndex];
            var answer = $(this).val().trim();
            examData.answers[question.id] = answer;
            
            // 更新题目导航
            updateQuestionNav();
        });
        
        // 上一题
        $('#prevBtn').click(function() {
            if (examData.currentQuestionIndex > 0) {
                showQuestion(examData.currentQuestionIndex - 1);
            }
        });
        
        // 下一题
        $('#nextBtn').click(function() {
            if (examData.currentQuestionIndex < examData.questions.length - 1) {
                showQuestion(examData.currentQuestionIndex + 1);
            }
        });
        
        // 提交答案
        $('#submitBtn').click(function() {
            submitAnswer();
        });
        
        // 提交答案
        function submitAnswer() {
            // 收集所有答案
            var answers = {};
            for (var i = 0; i < examData.questions.length; i++) {
                var question = examData.questions[i];
                var questionId = question.id;
                var userAnswer = '';
                
                if (question.questionType === 4) {
                    // 填空题 - 直接从input获取值
                    userAnswer = $('#fillBlankInput').val() || '';
                } else {
                    // 选择题 - 使用现有答案记录（已在selectOption和input事件中更新）
                    userAnswer = examData.answers[questionId] || '';
                }
                
                answers[questionId] = userAnswer;
            }
            
            // 提交答案
            $.ajax({
                url: ctx + "system/exam/pk/submitAnswer/" + examData.battleId,
                type: 'post',
                contentType: 'application/json;charset=UTF-8',
                data: JSON.stringify(answers),
                success: function(result) {
                    if (result.code == 0) {
                        // 提交成功，显示结果
                        var correctCount = result.data.correctCount || 0;
                        var totalQuestions = result.data.totalQuestions || examData.questions.length;
                        var score = result.data.score || 0;
                        
                        var message = '答题完成！<br>正确题数：' + correctCount + '/' + totalQuestions + '<br>得分：' + score + '分';
                        
                        // 显示结果并跳转
                        $.modal.alertSuccess(message, function() {
                            // 模态框关闭后的回调
                        });
                        
                        // 延迟跳转，确保提示信息能够显示
                        setTimeout(function() {
                            window.location.href = ctx + "system/exam/pk/index";
                        }, 1500);
                    } else {
                        $.modal.alertError(result.msg);
                    }
                },
                error: function() {
                    $.modal.alertError('提交答案失败，请稍后重试');
                }
            });
        }
        
        // 结束答题
        $('#finishBtn').click(function() {
            finishExam();
        });
        
        // 结束考试
        function finishExam() {
            // 收集所有答案
            var answers = {};
            var answeredCount = 0;
            
            for (var i = 0; i < examData.questions.length; i++) {
                var question = examData.questions[i];
                var questionId = question.id;
                var userAnswer = examData.answers[questionId] || '';
                
                if (userAnswer) {
                    answeredCount++;
                }
                
                answers[questionId] = userAnswer;
            }
            
            // 构建提示信息
            var message = '';
            if (answeredCount < examData.questions.length) {
                message = '还有' + (examData.questions.length - answeredCount) + '道题未作答，确定要提交吗？';
                // 确认是否提交
                $.modal.confirm(message, function() {
                    submitAllAnswers(answers);
                });
            } else {
                submitAllAnswers(answers);
            }
        }
        
        // 提交所有答案
        function submitAllAnswers(answers) {
            // 提交答案
            $.ajax({
                url: ctx + "system/exam/pk/submitAnswer/" + examData.battleId,
                type: 'post',
                contentType: 'application/json;charset=UTF-8',
                data: JSON.stringify(answers),
                success: function(result) {
                    if (result.code == 0) {
                        // 提交成功，显示结果
                        var correctCount = result.data.correctCount || 0;
                        var totalQuestions = result.data.totalQuestions || examData.questions.length;
                        var score = result.data.score || 0;
                        
                        var message = '答题完成！<br>正确题数：' + correctCount + '/' + totalQuestions + '<br>得分：' + score + '分';
                        
                        // 显示结果并跳转
                        $.modal.alertSuccess(message, function() {
                            // 跳转到PK对战首页
                            setTimeout(function() {
                               location.href  = ctx + "system/exam/pk/index";
                            }, 1000);
                        });
                    } else {
                        $.modal.alertError(result.msg);
                    }
                },
                error: function() {
                    $.modal.alertError('提交答案失败，请稍后重试');
                }
            });
        }
        
        // 更新题目导航
        function updateQuestionNav() {
            var navHtml = '';
            for (var i = 0; i < examData.questions.length; i++) {
                var questionId = examData.questions[i].id;
                var navClass = 'question-nav-item';
                if (i === examData.currentQuestionIndex) {
                    navClass += ' active';
                }
                if (examData.answers[questionId]) {
                    navClass += ' answered';
                }
                navHtml += '<div class="' + navClass + '" onclick="showQuestion(' + i + ')">' + (i + 1) + '</div>';
            }
            $('#question-nav-list').html(navHtml);
        }
        
        // 开始计时
        function startTimer() {
            updateTimerDisplay();
            examData.timerInterval = setInterval(function() {
                examData.remainingTime--;
                updateTimerDisplay();
                
                if (examData.remainingTime <= 0) {
                    clearInterval(examData.timerInterval);
                    $.modal.alertWarning('考试时间已结束，即将提交答卷');
                    setTimeout(function() {
                        finishExam();
                    }, 2000);
                }
            }, 1000);
        }
        
        // 更新计时器显示
        function updateTimerDisplay() {
            var totalSeconds = examData.remainingTime;
            var hours = Math.floor(totalSeconds / 3600);
            var minutes = Math.floor((totalSeconds % 3600) / 60);
            var seconds = totalSeconds % 60;
            
            var timeStr = padZero(hours) + ':' + padZero(minutes) + ':' + padZero(seconds);
            $('#timer').text(timeStr);
            
            // 时间少于10分钟时，高亮显示
            if (totalSeconds < 600) {
                $('#timer').css('color', '#f5222d');
            }
        }
        
        // 补零函数
        function padZero(num) {
            return num < 10 ? '0' + num : num;
        }
        
        // 更新导航按钮状态
        function updateNavigationButtons() {
            // 上一题按钮
            $('#prevBtn').prop('disabled', examData.currentQuestionIndex === 0);
            
            // 下一题按钮
            var isLastQuestion = examData.currentQuestionIndex === examData.questions.length - 1;
            $('#nextBtn').prop('disabled', true);
            $('#nextBtn').toggle(!isLastQuestion);
            
            // 结束按钮
            $('#finishBtn').toggle(isLastQuestion);
            
            // 提交按钮
            $('#submitBtn').show();
        }
        
        // 获取题目类型文本
        function getQuestionTypeText(type) {
            switch(type) {
                case 1: return '单选题';
                case 2: return '多选题';
                case 3: return '判断题';
                case 4: return '填空题';
                default: return '未知题型';
            }
        }
    </script>
</body>
</html>